package com.xiaoming.plugin.tcp.utils;

import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;

import java.nio.charset.Charset;

public class Params {

    public static Charset charset = Charset.forName("GBK");//hex

    public static boolean hexMsg = true; //16进制数据传输模式
    public static boolean isCheck = false; //16进制数据传输模式
    public static int receiveDelayMs = 0; //接收延迟毫秒
    public static String hexHead = "FAFBFCFD"; //消息头（处理闭包用）
    public static String regex = ""; //消息头（处理闭包用）23.{18}2A
    public static int hexDataLengthIndex = 0; //数据长度位（处理粘包用，从head之后开始算，第一个hex数下标是0）
    public static int hexDataOtherLength = 0; //其余长度（处理闭包用，全文长度=head长度+data长度+数据长度位1+其余长度）

    public static void initParams(JSONObject param) {

        try {
            if (param != null) {
                String p_charset = param.getString("charset");
                if (p_charset == null || "".equals(p_charset)) {
                } else {
                    charset = Charset.forName("GBK");
                }

                String _hexMsg = param.getString("hexMsg");
                if (_hexMsg == null || "".equals(_hexMsg)) {
                } else {
                    if ("true".equals(_hexMsg.toLowerCase())) {
                        hexMsg = true;
                    } else {
                        hexMsg = false;
                    }
                }
                isCheck = param.getBooleanValue("isCheck");
                String regex = param.getString("regex");
                if (!TextUtils.isEmpty(regex)) {
                    Params.regex = regex;
                }
                String _hexDataLengthIndex = param.getString("hexDataLengthIndex");
                if (_hexMsg == null || "".equals(_hexMsg)) {
                } else {
                    hexDataLengthIndex = Integer.parseInt(_hexDataLengthIndex);
                }

                String p_receiveDelayMs = param.getString("receiveDelayMs");
                if (p_receiveDelayMs == null || "".equals(p_receiveDelayMs)) {
                } else {
                    receiveDelayMs = Integer.parseInt(p_receiveDelayMs);
                }
            }
        } catch (Exception ex) {
            throw ex;
        } finally {
            //由于计算字符串下标，所以乘以2，因为16进制一个数占2位
            hexDataLengthIndex *= 2;
            hexDataOtherLength *= 2;
            hexDataLengthIndex += hexHead.length();
        }
    }
}
